package com.wltt.product.ahuthr.config.exception;

import com.wltt.product.ahuthr.model.ResultData;
import com.wltt.product.ahuthr.utils.ResponseUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常，该异错误信息直接作为页面返回值
     *
     * @param e 异常信息
     */
    @ExceptionHandler(value = BusinessException.class)
    public void businessExceptionExceptionHandler(HttpServletResponse response,
                                                  BusinessException e) throws Exception {
        ResponseUtil.writeResponse(response, e.getHttpStatus(), ResultData.failure(e.getMessage()));
    }

    @ExceptionHandler(value = Exception.class)
    public void exceptionHandler(HttpServletResponse response,
                                 Exception e) throws Exception {
        e.printStackTrace();
        logger.error(e);
        ResponseUtil.writeResponse(response, HttpStatus.BAD_REQUEST, ResultData.failure("未知错误"));
    }

    @ExceptionHandler(value = Throwable.class)
    public void throwableHandler(HttpServletResponse response,
                                 Throwable t) throws Exception {
        logger.error(t);
        ResponseUtil.writeResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, ResultData.failure("内部错误"));
    }
}
